package com.mk.admin.schedule;


import com.mk.admin.mapper.DictionaryMapper;
import com.mk.admin.mapper.MedicalTechnologyMapper;
import com.mk.admin.model.dto.DictionaryDto;
import com.mk.admin.model.entity.DictionaryEntity;
import com.mk.admin.model.vo.MedicalTechnologyProjectRemoteVo;
import com.mk.admin.service.DepartmentService;
import com.mk.admin.service.MedicalTechnologyProjectService;
import com.mk.admin.service.MedicalTechnologyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 得到医技预约（检验检查项目），
 * 因不经常变动，可设置每天执行一次
 * 亦可单独刷新 在医技预约里面
 */
@Configuration
@EnableScheduling
public class TaskGetMedicalTechnologyProject implements SchedulingConfigurer {
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private MedicalTechnologyProjectService medicalTechnologyProjectService;
    @Value("${spring.profiles.active}")
    private String dev;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        if ("dev".equals(dev)) {
            return;
        }
        scheduledTaskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    DictionaryEntity entity = new DictionaryEntity();
                    entity.setCode("TaskMedicalTechnologyProject");
                    entity.setStatus(1);
                    List<DictionaryDto> list = dictionaryMapper.select(entity);
                    String cron = "0 0 0/1 * * ?";//每小时执行一次
                    if (list.size() > 0) {
                        cron = list.get(0).getDescribe();
                        medicalTechnologyProjectService.fresh(new MedicalTechnologyProjectRemoteVo());
                    }

                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}
